
//
//  ThemeManager.m
//  weibo-01
//
//  Created by HZApple on 16/5/10.
//  Copyright © 2016年 hdu. All rights reserved.
//

#import "ThemeManager.h"

@implementation ThemeManager

+ (instancetype)sharedManager {
    static ThemeManager *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [self sharedManager];
}
- (id)copy {
    return self;
}

#pragma mark 
- (instancetype)init {
    if (self = [super init]) {
        
        _themeName = @"Ocean Run";
       NSString *savedThemeName = [[NSUserDefaults standardUserDefaults] objectForKey:kThemeName];
      
        if (savedThemeName.length > 0) {
            _themeName = savedThemeName;
        }
        
     _themeConfig =  [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Theme.plist" ofType:nil]];
     
    [self _loadColorConfigFile];
    }
    return self;
}

- (void)_loadColorConfigFile {
    
    NSString *themePath = [self themePath];
    
    NSString *configFilePath = [themePath stringByAppendingPathComponent:@"config.plist"];
    
    _themeColorName = [NSDictionary dictionaryWithContentsOfFile:configFilePath];
    
}

- (void)setThemeName:(NSString *)themeName {
    if (_themeName != themeName) {
        _themeName = [themeName copy];
        
        [self _loadColorConfigFile];
        //将数据存入plist文件
        [[NSUserDefaults standardUserDefaults] setObject:_themeName forKey:kThemeName];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kThemeChangeNotification object:nil];
    }
}

- (NSString *)themePath {
    
    NSString *path = self.themeConfig[_themeName];
    
    
    NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
    
    NSString *themePath = [bundlePath stringByAppendingPathComponent:path];
    
    return themePath;
    
}



- (UIImage *)themeImageWithImageName:(NSString *)imageName {
    
    NSString *themePath = [self themePath];
    
     NSString *imagePath = [themePath stringByAppendingPathComponent:imageName];
    
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    
    return image;
}

- (UIColor *)themeColorWithColorName:(NSString *)colorName {
    
    NSDictionary *rgbDIc = _themeColorName[colorName];
    
    CGFloat r = [rgbDIc[@"R"] floatValue] / 255;
    CGFloat g = [rgbDIc[@"G"] floatValue] / 255;
    CGFloat b = [rgbDIc[@"B"] floatValue] / 255;
    
    CGFloat alpha = rgbDIc[@"alpha"]? [rgbDIc[@"alpha"] floatValue]:1;
    
  
    
    return [UIColor colorWithRed:r green:g blue:b alpha:alpha];
}

@end
